﻿using System;
using System.Collections.Generic;
using Kugar.Core.BaseStruct;
using Kugar.Core.ExtMethod;
using Kugar.Core.Web;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Kugar.UI.Web.AdminLTE.Controllers
{
    public abstract class WebUIBaseController : Controller
    {
        private List<VM_MVCMsgBoxItem> _msgList = null;
        private Lazy<Dictionary<string,CommandHandler>> _dic=new Lazy<Dictionary<string, CommandHandler>>(createHandlers); 

        public virtual IActionResult AjaxCommandHandler()
        {
            var cmdName = Request.GetString("MethodName");

            var handler = _dic.Value.TryGetValue(cmdName);

            if (handler!=null)
            {
                var ret=handler(cmdName);

                return this.NewtonJson(ret);
            }
            else
            {
                return StatusCode(404);
            }
        }

        protected void RegisterCommandHander(string cmdName, CommandHandler handler)
        {
            _dic.Value.Add(cmdName,handler);
        }

        protected WebUIBaseController()
        {
            _msgList = new List<VM_MVCMsgBoxItem>();
        }

        protected void MsgBox(string message)
        {
            MsgBoxAndScript(msg:message);
        }

        protected void MsgBoxAndRefresh(string msg)
        {
            MsgBoxAndGoto(msg,this.Request.GetDisplayUrl());
        }

        protected void MsgBoxAndGoto(string msg, string url)
        {
            MsgBoxAndScript(msg, $"WebUIJS.GoTo('{url}',this);");
        }

        protected void MsgBoxAndScript(string msg, string script="")
        {
            if (string.IsNullOrWhiteSpace(msg) && string.IsNullOrWhiteSpace(script))
            {
                return;
            }

            List<VM_MVCMsgBoxItem> msgList = null;

            if (ViewBag.MsgData_Temp ==null)
            {
                ViewBag.MsgData_Temp =_msgList;
            }

            msgList = _msgList;

            msgList.Add(new VM_MVCMsgBoxItem(msg, script));
        }

        protected void MsgBoxAndCloseModal(string msg,bool isRefreshPage=false)
        {
            var layerIndex = Request.GetString("layerindex");

            string script;

            if (string.IsNullOrWhiteSpace(layerIndex))
            {
                script = "WebUIJS.CloseModal();";
            }
            else
            {
                script = $"WebUIJS.CloseModal('{layerIndex}');";
            }

            if (isRefreshPage)
            {
                script += "WebUIJS.Loading(); WebUIJS.Refresh();";
            }

            this.MsgBoxAndScript(msg,script);
        }

        protected void MsgBoxAndCallbackData(string msg, JObject callbackData,bool isCloseModal=false)
        {
            var callbackID = Request.GetString("CallbackID");

            var layerIndex = Request.GetString("layerindex");

            string script;

            if (string.IsNullOrWhiteSpace(layerIndex))
            {
                script = "WebUIJS.CloseModal();";
            }
            else
            {
                script = $"WebUIJS.CloseModal('{layerIndex}');";
            }

            if (!string.IsNullOrWhiteSpace(callbackID))
            {
                MsgBoxAndScript(msg,$"__callFuncByID('{callbackID}',{callbackData.ToString(Formatting.None)});{(isCloseModal? script : "")}");
            }
            else
            {
                MsgBoxAndScript(msg,isCloseModal? script : "");
            }
            
        }

        private List<VM_MVCMsgBoxItem> getMsgList()
        {
            return new List<VM_MVCMsgBoxItem>();
        }

        private static Dictionary<string, CommandHandler> createHandlers()
        {
            return new Dictionary<string, CommandHandler>(StringComparer.CurrentCultureIgnoreCase);
        }

        /// <summary>
        /// 获取经过授权后的当前用户ID,读取的是 HttpContext.User.FindFirst("userid")
        /// </summary>
        /// <returns></returns>
        protected string GetCurrentUserId()
        {
            return HttpContext.User.FindFirst("UserID")?.Value.ToStringEx();
        }


        /// <summary>
        /// 获取当前登录授权使用的SchemeName
        /// </summary>
        /// <returns></returns>
        protected string GetCurrentSchemeName()
        {
            return HttpContext.Items.TryGetValue("SchemeName", "").ToStringEx();
        }
    }

    public delegate ResultReturn CommandHandler(string cmdName);
}